<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑学生' : '添加学生' }}</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          @click="goBack">
          返回列表
        </el-button>
      </div>
      
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="form" 
        label-width="100px"
        v-loading="loading"
      >
        <el-form-item label="学号" prop="username">
          <el-input v-model="form.username" placeholder="请输入学号"></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" placeholder="请输入密码，不填则使用默认密码"></el-input>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校" filterable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getStudentDetail, addStudent, updateStudent } from '@/api/student';
import { getSchoolList } from '@/api/school';

export default {
  name: 'StudentEdit',
  data() {
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (value && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    };
    
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    
    return {
      // 是否为编辑模式
      isEdit: false,
      // 表单对象
      form: {
        id: undefined,
        username: '',
        nickname: '',
        password: '',
        schoolId: undefined,
        educationLevel: undefined,
        email: '',
        phone: ''
      },
      // 表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        schoolId: [
          { required: true, message: '请选择学校', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      // 学校选项
      schoolOptions: [],
      // 加载状态
      loading: false,
      // 提交按钮加载状态
      submitLoading: false
    };
  },
  created() {
    // 获取路由参数中的ID
    const id = this.$route.params.id;
    if (id) {
      this.isEdit = true;
      this.getStudentDetail(id);
    }
    
    // 获取学校列表
    this.getSchools();
  },
  methods: {
    // 获取学生详情
    getStudentDetail(id) {
      this.loading = true;
      getStudentDetail(id).then(response => {
        this.form = response.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取学生信息失败');
        this.goBack();
      });
    },
    
    // 获取学校列表
    getSchools() {
      getSchoolList(1, 100).then(response => {
        this.schoolOptions = response.data.records.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          
          const request = this.isEdit ? updateStudent(this.form) : addStudent(this.form);
          request.then(() => {
            this.$message.success(this.isEdit ? '更新成功' : '添加成功');
            this.goBack();
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      if (this.isEdit) {
        // 如果是编辑模式，重新获取详情
        this.getStudentDetail(this.form.id);
      }
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/students');
    }
  }
};
</script> 